//
//  StatusCellPictureView.swift
//  Weibo
//
//  Created by 张婷 on 15/10/28.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

/// 配图视图格子间距
let StatusPictureViewItemMargin: CGFloat = 8

/// Cell 可重用标示符
let StatusPictureViewCellId = "StatusPictureViewCellId"

class StatusCellPictureView: UICollectionView {
    
    /// 微博视图模型
    var viewModel: StatusViewModel? {
        didSet {
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    ///  MARK: 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        layout.scrollDirection = .Horizontal
        //layout.sectionInset = UIEdgeInsets(top: StatusPictureViewItemMargin, left: StatusPictureViewItemMargin, bottom: StatusPictureViewItemMargin, right: StatusPictureViewItemMargin)
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        self.registerClass(StatusCellPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewCellId)
        
        dataSource = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: - 视图大小
extension StatusCellPictureView {
    
    ///  计算 pictureView 视图大小
    private func calcViewSize() -> CGSize {
        
        /// 默认每行 3 张图片
        let rowCount: CGFloat = 3
        
        /// 最大宽度
        let maxWidth: CGFloat = UIScreen.mainScreen().bounds.width - 2 * StatusPictureViewItemMargin
        
        /// 每个 item 的宽度
        let itemWidth: CGFloat = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        /// 图片数量
        let imageCount = viewModel?.thumbnailUrls?.count ?? 0
        
        /// 无图
        if imageCount == 0 {
            return CGSizeZero
        }
        
        /// 单图
        if imageCount == 1 {
            
            // TODO: 临时设置单图的大小
            return CGSize(width: 150, height: 120)
        }
        /// 4张图
        if imageCount == 4 {
            let w = 2 * itemWidth + StatusPictureViewItemMargin
            return CGSize(width: w, height: w)
        }
        /// 其他张
        let row = CGFloat((imageCount - 1) / Int(rowCount) + 1)
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        
        return CGSize(width: w, height: h)
    }
}

// MARK: - UICollectionViewDataSource
extension StatusCellPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = self.dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellId, forIndexPath: indexPath) as! StatusCellPictureViewCell
        
        cell.thumbnailUrl = viewModel?.thumbnailUrls![indexPath.item]
        
        return cell
    }
}

/// 微博视图配图 Cell
class StatusCellPictureViewCell: UICollectionViewCell {
    
    var thumbnailUrl: NSURL?{
        didSet {
            
            //print(thumbnailUrl)
            backgroundColor = UIColor(white: 0.7, alpha: 1.0)
            iconView.sd_setImageWithURL(thumbnailUrl, placeholderImage: nil, options: [.RetryFailed, .LowPriority])
        }
    }
    
    ///  MARK: 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///  MARK: - 懒加载控件
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        
        ///  设置填充模式
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    
    }()
    
    private func setupUI() {
        
         contentView.addSubview(iconView)
         iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    
    }
}


